<template>
  <div class="map-container">
    <div id="container"></div>
    <div class="sidebar">
  <div class="search-box"><el-input v-model="searchKeyword" placeholder="搜索自提点" suffix-icon="Search" @keyup.enter="handleSearch"></el-input></div>
  <div class="location-info">
        <h3>选址信息</h3>
        <p>坐标: <span id="lnglat">{{ currentPoint.lnglat || '未选择' }}</span></p>
        <p>地址: <span id="address">{{ currentPoint.address || '未选择' }}</span></p>
      </div>
      <el-form ref="formRef" :model="pointForm" label-width="100px" class="point-form">
        <el-form-item label="id" prop="id">
          <el-input v-model="pointForm.id" placeholder="请输入自提点ID"></el-input>
        </el-form-item>
        <el-form-item label="自提点名称" prop="name" :rules="[{ required: true, message: '请输入名称'}]">
          <el-input v-model="pointForm.name" placeholder="请输入自提点名称"></el-input>
        </el-form-item>
        <el-form-item label="联系人" prop="contact_name" :rules="[{ required: true, message: '请输入联系人'}]">
          <el-input v-model="pointForm.contact_name" placeholder="请输入联系人"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone" :rules="[{ required: true, message: '请输入电话'}]">
          <el-input v-model="pointForm.phone" placeholder="请输入联系电话"></el-input>
        </el-form-item>
        <el-form-item label="自提点图片">
          <div v-if="pointForm.image" style="margin-bottom: 10px;">
            <img
              :src="baseUrl + pointForm.image"
              alt="自提点图片"
              style="width: 100px; height: 100px; object-fit: cover; border-radius: 8px;"
            />
          </div>
          <el-upload
            action="http://192.168.90.26:8080/uploade/uploading"
            list-type="picture-card"
            :auto-upload="true"
            :on-success="handleUploadSuccess"
            :limit="1"
            :on-exceed="handleExceed"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="savePoint">保存</el-button>
          <el-button @click="resetForm">取消</el-button>
          <el-button type="danger" v-if="pointForm.id" @click="deletePoint">删除</el-button>
        </el-form-item>
      </el-form>
      <div class="points-list">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;"><h3>已保存自提点</h3><span class="count">(共 {{ pointsList.length }} 个)</span></div>
        <el-table :data="pointsList" @row-click="handleRowClick" class="points-table">
          <el-table-column prop="id" label="ID"></el-table-column>
          <el-table-column prop="name" label="名称"></el-table-column>
          <el-table-column prop="contact_name" label="联系人"></el-table-column>
          <el-table-column prop="phone" label="电话"></el-table-column>
          <el-table-column label="图片">
            <template #default="{ row }">
              <div v-if="row.image" style="display: flex; justify-content: center;">
                <img
                  :src="baseUrl+ row.image"
                  alt="自提点图片"
                  style="width: 100px; height: 100px; object-fit: cover; border-radius: 8px;"
                />
              </div>
              <div v-else>无图片</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script setup>
import { onMounted, onUnmounted, ref, reactive } from "vue";import { ElMessage, ElForm } from "element-plus";import axios from "axios";
import AMapLoader from "@amap/amap-jsapi-loader";
const baseUrl=ref("http://192.168.90.26:8080/")
let map = null;
let markers = [];
function handleExceed() {
  alert('最多只能上传1张图片');
  return false;
}
function handleUploadSuccess(res) {
  pointForm.image=res
}
// 当前选中的坐标点
const currentPoint = ref({
  lnglat: '',
  address: ''
});

// 表单数据
const pointForm = reactive({
  id: null,
  name: '',
  contact_name: '',
  phone: '',
  lnglat: '',
  address: '',
  image: ''
});

// 搜索功能
const searchKeyword = ref('');
const mapLoaded = ref(false);
const handleSearch = () => {
  if (!mapLoaded.value) {
    ElMessage.warning('地图尚未加载完成，请稍后再试');
    return;
  }
  fetchPoints();
};

// 自提点列表
const pointsList = ref([]);

// 获取自提点列表
const fetchPoints = () => {
  let url = 'http://192.168.90.26:8080/pickup_point/list';
  if (searchKeyword.value) {
    url += `?name=${searchKeyword.value}`;
  }
  axios.get(url).then(res => {
    pointsList.value = res.data;
    // 添加标记到地图
    addMarkersToMap();
  }).catch(err => {
    ElMessage.error('获取自提点失败');
    console.error(err);
  });
};

// 添加标记到地图
const addMarkersToMap = () => {
  if (!map) {
    console.error('地图尚未初始化，无法添加标记');
    return;
  }
  // 清除现有标记
  markers.forEach(marker => marker.remove());
  markers = [];

  // 添加新标记
  pointsList.value.forEach(point => {
    const [lng, lat] = point.lnglat.split(',').map(Number);
    const marker = new AMap.Marker({
      position: new AMap.LngLat(lng, lat),
      title: point.name
    });
    map.add(marker);
    // 标记点击事件
    marker.on('click', () => {
      pointForm.id = point.id;
      pointForm.name = point.name;
      pointForm.contact_name = point.contact_name;
      pointForm.phone = point.phone;
      pointForm.lnglat = point.lnglat;
      pointForm.address = point.address;
      pointForm.image = point.image;
      currentPoint.value = {
        lnglat: point.lnglat,
        address: point.address
      };
      // 移动地图到标记位置
      map.setCenter([lng, lat]);
    });
    markers.push(marker);
  })
}
// 保存自提点
const savePoint = () => {
  if (!currentPoint.value.lnglat) {
    ElMessage.warning('请先在地图上选择位置');
    return;
  }
  pointForm.lnglat = currentPoint.value.lnglat;
  pointForm.address = currentPoint.value.address;

  const method = pointForm.id ? 'get' : 'post';
  axios[method]('http://192.168.90.26:8080/pickup_point/add', pointForm).then(res => {
    ElMessage.success(pointForm.id ? '修改成功' : '添加成功');
    resetForm();
    fetchPoints();
  }).catch(err => {
    ElMessage.error(pointForm.id ? '修改失败' : '添加失败');
    console.error(err);
  });
};

// 重置表单
const resetForm = () => {
pointForm.id = null;pointForm.name = '';pointForm.contact_name = '';pointForm.phone = '';pointForm.lnglat = '';pointForm.address = '';pointForm.image = '';
};

// 删除自提点
const deletePoint = () => {
  if (!pointForm.id){
    ElMessage.warning('请选择要删除的项');
    return;
  }

  axios.get("http://192.168.90.26:8080/pickup_point/delete?id="+pointForm.id).then(res => {
    if (!res.data) {
      ElMessage.error('删除失败');
      return;
    }
    ElMessage.success('删除成功');
    resetForm();
    fetchPoints();
  }).catch(err => {
    ElMessage.error('删除失败');
    console.error(err);
  });
};

// 点击列表行
const handleRowClick = (row) => {
  pointForm.id = row.id;
  pointForm.name = row.name;
  pointForm.contact_name = row.contact_name;
  pointForm.phone = row.phone;
  pointForm.lnglat = row.lnglat;
  pointForm.address = row.address;
  pointForm.image = row.image;
  currentPoint.value = {
    lnglat: row.lnglat,
    address: row.address
  };
  const [lng, lat] = row.lnglat.split(',').map(Number);
  map.setCenter([lng, lat]);
};

// 动态加载 JSAPI 和 UI 库
function loadAMapScript() {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = `//webapi.amap.com/maps?v=2.0&key=fdb568b65d6b8d3fded00fda9d7ff271&plugin=AMap.Scale`;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

function loadAMapUI() {
  return new Promise((resolve, reject) => {
    const script = document.createElement("script");
    script.src = "//webapi.amap.com/ui/1.1/main.js";
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
}

onMounted(async () => {
  window._AMapSecurityConfig = {
    securityJsCode: "f3e80ed5c792483d8a4d515980b918a8",
  };

  try {
    await loadAMapScript();
    await loadAMapUI();

    AMapLoader.load({
      key: "fdb568b65d6b8d3fded00fda9d7ff271",
      version: "2.0",
      plugins: ["AMap.Scale"],
    }).then((AMap) => {
  map = new AMap.Map("container", {
    zoom: 16,
    viewMode: "2D", //设置地图模式
  });

  // 加载 PositionPicker 插件
  AMapUI.loadUI(["misc/PositionPicker"], function (PositionPicker) {
    const positionPicker = new PositionPicker({
      mode: "dragMap",
      map: map,
    });

    positionPicker.on("success", function (positionResult) {
      const lnglat = positionResult.position.lng + ',' + positionResult.position.lat;
      currentPoint.value.lnglat = lnglat;
      currentPoint.value.address = positionResult.address;
      // addTempMarker(positionResult.position);
    });

    positionPicker.on("fail", function () {
      document.getElementById("lnglat").innerHTML = " ";
      document.getElementById("address").innerHTML = " ";
    });

    positionPicker.start();
  });

  // 定位插件
  AMap.plugin("AMap.Geolocation", function () {
    const geolocation = new AMap.Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      offset: [10, 20],
      zoomToAccuracy: true,
      position: "RB",
    });

    geolocation.getCurrentPosition(function (status, result) {
      if (status === "complete") {
        onComplete(result);
      } else {
        onError(result);
      }
    });

    function onComplete(data) {}
    function onError(data) {}
  });

  mapLoaded.value = true;
    fetchPoints(); // 地图初始化完成后再加载数据
    });

      // 加载 PositionPicker 插件
      AMapUI.loadUI(["misc/PositionPicker"], function (PositionPicker) {
        const positionPicker = new PositionPicker({
          mode: "dragMap",
          map: map,
        });

        positionPicker.on("success", function (positionResult) {
          const lnglat = positionResult.position.lng + ',' + positionResult.position.lat;
          currentPoint.value.lnglat = lnglat;
          currentPoint.value.address = positionResult.address;
        });

        positionPicker.on("fail", function () {
          document.getElementById("lnglat").innerHTML = " ";
          document.getElementById("address").innerHTML = " ";
        });

        positionPicker.start();
      });

      // 定位插件
      AMap.plugin("AMap.Geolocation", function () {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          offset: [10, 20],
          zoomToAccuracy: true,
          position: "RB",
        });

        geolocation.getCurrentPosition(function (status, result) {
          if (status === "complete") {
            onComplete(result);
          } else {
            onError(result);
          }
        });

        function onComplete(data) {}
        function onError(data) {}
      });
  } catch (e) {
    console.error("加载地图资源失败", e);
  }
});

onUnmounted(() => {
  map?.destroy();
});
</script>


<style scoped>
.map-container {
  display: flex;
  gap: 20px;
  padding: 20px;
}

#container{
  padding:0;
  margin: 0;
  width: 70%;
  height: 600px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.sidebar {
  width: 45%;
  display: flex;
  flex-direction: column;
  gap: 20px;
}
.search-box { margin-bottom: 15px; display: flex; align-items: center; gap: 10px; padding: 0 15px; }
.points-list .count { color: #666; font-size: 14px; }

.location-info {
  padding: 15px;
  background: #f5f5f5;
  border-radius: 8px;
}
.points-table {
  width: 100%;
}
.point-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.points-list {
  background: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  flex-grow: 1;
  overflow: auto;
}

.el-table {
  width: 100%;
}
</style>